package com.project.nimsen.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.project.jdbc.dao.IBaseJdbcDao;
import com.project.jdbc.service.BaseServiceImpl;
import com.project.jdbc.utils.Finder;
import com.project.nimsen.dao.IBaseDao;
import com.project.nimsen.dto.RoleAuthorDto;
import com.project.nimsen.entity.RoleAuthor;
import com.project.nimsen.service.IRoleAuthorService;
import com.project.nimsen.util.NimsenUtil;
@Repository("roleAuthorService")
public class RoleAuthorServiceImpl extends BaseServiceImpl implements
		IRoleAuthorService {
	@Resource
	IBaseDao baseDao;
	protected IBaseJdbcDao getBaseDao() {
		return baseDao;
	}
	public List<Map<String, Object>> findByDto(RoleAuthorDto dto)
			throws Exception {
		Finder finder = new Finder("select * from roleauthor"
			+ " where active!=1");
		if(StringUtils.isNotBlank(dto.getRoleid())){
			finder.append(" and roleid=:roleid");
			finder.setParam("roleid", dto.getRoleid());
		}
		return baseDao.queryForList(finder);
	}
	public boolean saveByDto(RoleAuthorDto dto) throws Exception {
		if(dto==null||StringUtils.isBlank(dto.getRoleid())||StringUtils.isBlank(dto.getCuruseid()))
			return false;
		String roleid = dto.getRoleid();
		//把原有的用户权限表信息去掉
		Finder upFinder = new Finder("update roleauthor set active=1 where active!=1 and roleid=:roleid");
		upFinder.setParam("roleid", roleid);
		baseDao.update(upFinder);
		//添加现有的用户权限信息
		String strauthor = dto.getAuthorids();
		if(StringUtils.isBlank(strauthor))
			return true;
		List<String> authorids = NimsenUtil.convertStr2List(strauthor);
		List<RoleAuthor> authors = new ArrayList<RoleAuthor>();
		Date nowDate = new Date();
		String curuseid = dto.getCuruseid();
		for(String authorid : authorids){
			RoleAuthor author = new RoleAuthor();
			author.setActive(new Integer(0));
			author.setCreateTime(nowDate);
			author.setCreateUser(curuseid);
			author.setAuthorid(authorid);
			author.setRoleid(roleid);
			authors.add(author);
		}
		return baseDao.saveList(authors).size()>0;
	}

}
